// src/parsers/universal/babelV2UniversalParser.ts
import * as babelParser from '@babel/parser';
import type * as t from '@babel/types';
import { babelService } from '@/services/babelService'; // Use centralized Babel service
import { BabelV2AstProcessor } from './babelV2AstProcessor'; // Import the V2 processor
import type { UniversalFlowNode, UniversalFlowEdge, SourceFormat } from '@/models/universalFlow';
import type { ParseUniversalResult } from '@/parsers/universalParser'; // Reuse interface

/**
 * Default Babel parser options suitable for modern JS/TS with JSX.
 * (You might centralize this if used elsewhere)
 */
const defaultParserOptions: babelParser.ParserOptions = {
    sourceType: 'module',
    plugins: [
        'typescript',
        'jsx'
    ],
    // Add other options if needed
};

/**
 * Parses JavaScript/TypeScript code using Babel Parser and the V2 AST Processor.
 *
 * @param content The code content (string).
 * @param format The source format ('javascript' or 'typescript').
 * @param options Optional Babel parser options to override defaults.
 * @returns A Promise resolving to the ParseUniversalResult.
 */
export async function parseBabelV2ToUniversal(
    content: string,
    format: SourceFormat,
    options?: babelParser.ParserOptions
): Promise<ParseUniversalResult> {
    console.log(`[Babel V2 Parser] Attempting to parse ${format} content...`);
    try {
        const ast = await babelService.parseCode(content, { ...defaultParserOptions, ...options });
        console.log('[Babel V2 Parser] Parsing successful. Calling V2 AST Processor...');

        // --- Instantiate the V2 Processor ---
        const processor = new BabelV2AstProcessor(ast, format);

        // --- CORRECTED: Call processAst() instead of process() ---
        const { nodes, edges, rootId } = processor.processAst();
        // const { nodes, edges, rootId } = processor.process(ast); // OLD INCORRECT CALL

        console.log(`[Babel V2 Parser] V2 Processing complete. Nodes: ${nodes.length}, Edges: ${edges.length}`);

        return {
            success: true,
            nodes: nodes,
            edges: edges,
            rootId: rootId,
            rawDocument: ast // Keep the raw AST if needed downstream
        };

    } catch (error: any) {
        console.error('[Babel V2 Parser] Error during parsing or V2 processing:', error);
        return {
            success: false,
            error: `Babel Parse/Process Error: ${error.message || 'Unknown error'}`,
            nodes: [],
            edges: [],
            rootId: null,
        };
    }
}